package cm.utils;

import cm.enums.ExportTypeEnum;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author yxh
 * @Description: 设置下载相应
 * @Date: Created in 2022/8/18 11:13
 * @Modified By:
 */
@Slf4j
public class DownloadResponseUtil {
    /**
     * 设置下载响应
     *
     * @param fileName
     * @param bytes
     * @param response
     */
    public static void responseSetProperties(String fileName, byte[] bytes, HttpServletResponse response, String contentType) {
        OutputStream outputStream = null;
        try {
            response = setResponse(fileName, response, contentType);
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
        } catch (IOException e) {
            log.error("iostream error:{}", e.getMessage(), e);
        } finally {
            closeStream(outputStream);
        }
    }

    public static void responseSetProperties(String fileName, ExcelWriter writer, HttpServletResponse response, String contentType) {
        OutputStream outputStream = null;
        try {
            response = setResponse(fileName, response, contentType);
            outputStream = response.getOutputStream();
            writer.flush(outputStream, true);
        } catch (IOException e) {
            log.error("iostream error:{}", e.getMessage(), e);
        } finally {
            closeStream(outputStream);
        }
    }

    public static void closeStream(OutputStream outputStream) {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            log.error("iostream close IOException:{}", e.getMessage(), e);
        }
    }

    public static HttpServletResponse setResponse(String fileName, HttpServletResponse response, String contentType) {
        try {
            contentType = StringUtils.isEmpty(contentType) ? ExportTypeEnum.XLSX.getValue() : ExportTypeEnum.find(contentType);
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
            response.setContentType(contentType);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "max-age=30");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        } catch (IOException e) {
            log.error("iostream error:{}", e.getMessage(), e);
        }
        return response;
    }
}
